package com.lease.web.admin.custom.converter;

import com.lease.model.enums.BaseEnum;
import org.springframework.core.convert.converter.Converter;
import org.springframework.core.convert.converter.ConverterFactory;

public class StringToBaseEnumConverterFactory implements ConverterFactory<String, BaseEnum> {

    @Override
    public <T extends BaseEnum> Converter<String, T> getConverter(Class<T> targetType) {
        return new Converter<String, T>() {
            @Override
            public T convert(String source) {
                if (source == null || source.isEmpty()) {
                    return null;
                }
                try {
                    Integer code = Integer.valueOf(source);
                    for (T enumValue : targetType.getEnumConstants()) {
                        if (enumValue.getCode().equals(code)) {
                            return enumValue;
                        }
                    }
                } catch (NumberFormatException e) {
                    // 尝试通过name匹配
                    for (T enumValue : targetType.getEnumConstants()) {
                        if (enumValue.getName().equalsIgnoreCase(source)) {
                            return enumValue;
                        }
                    }
                }
                return null;
            }
        };
    }
}
